package obecto.utility
{
	import flash.display.DisplayObject;
	
	import mx.utils.StringUtil;
	
	import obecto.core.FLUIComponent;
	import obecto.metadata.PartDirective;
	
	public class PartUtility
	{
		public static function initializePart(
			component : FLUIComponent, view : DisplayObject, directive : PartDirective) : DisplayObject 
		{
			var part : DisplayObject = resolvePart(view, directive.path, directive.optional);
			
			component[directive.name] = part;
			
			return part;
		}
		
		public static function removePart(
			component : FLUIComponent, view : DisplayObject, directive : PartDirective) : void 
		{
			component[directive.name] = null;
		}
		
		private static function resolvePart(view : DisplayObject, path : String, optional : String) : DisplayObject 
		{
			var segments : Array = path.split(".");
			var clip : DisplayObject = view;
			var segment : String;
			
			try
			{
				for (var i : int = 0; i < segments.length; i++)
				{
					segment = segments[i];
					
					if (clip[segment] != null)
					{
						clip = clip[segment];
						continue;
					}
					else
					{
						var currentPath : String = segments.slice(0, i+1).join(".");
						var errorMessage : String = StringUtil.substitute(
							"{0} from {1} is invalid path", currentPath, path);
								
						throw new Error(errorMessage);
					}
				}
			}
			catch(e : Error)
			{
				if(optional == "true")
				{
					clip = null;
				}
				else
				{
					throw e;
				}
			}
			
			return clip;
		}
	}
}